<template>
    <div>
        <div style="padding: 10px;">

            <!--            搜索区域-->
            <div style="margin:10px 0;">
                <el-input v-model="search" placeholder="请输入关键字" style="width: 20%;" clearable/>
                <el-button type="primary" style="margin-left: 5px;" @click="load"> 查询</el-button>
                <el-button type="primary" style="margin-left: 5px;" @click="add"> 添加</el-button>
            </div>
            <el-table
                    :data="tableData"
                    style="width: 100%;"
                    stripe
                    row-key="id"
                    default-expand-all
            >
                <el-table-column type="selection" width="55"></el-table-column>
                <el-table-column prop="id" label="ID" width="200"></el-table-column>
                <el-table-column prop="name" label="名称" width="200"></el-table-column>
                <el-table-column prop="flag" label="唯一标识"></el-table-column>
                <el-table-column prop="description" label="描述" ></el-table-column>
                <!--操作-->
                <el-table-column label="操作">
                    <template #default="scope">
                        <el-button size="small" type="info" @click="selectMenu(scope.row)"
                        ><i class="el-icon-menu"></i> 分配菜单
                        </el-button>
                        <el-button size="small" @click="handleEdit(scope.$index, scope.row)"
                        ><i class="el-icon-edit-outline"></i> 编辑
                        </el-button>

                        <el-popconfirm
                                class="ml-5"
                                confirm-button-text='确定'
                                cancel-button-text='我再想想'
                                icon="el-icon-info"
                                icon-color="red"
                                title="您确定删除吗？"
                                @confirm="handleDelete(scope.$index,scope.row)"
                        >
                            <el-button type="danger" size="small" slot="reference"><i
                                    class="el-icon-remove-outline"></i> 删除
                            </el-button>
                        </el-popconfirm>

                    </template>
                </el-table-column>
            </el-table>
            <!--            分页栏-->
            <div style="margin: 10px 0;">
                <el-pagination
                        v-model:pageNum="pageNum"
                        :page-sizes="[5, 10, 20]"
                        :page-size="pageSize"
                        layout="total, sizes, prev, pager, next, jumper"
                        :total="total"
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"
                >
                </el-pagination>

                <!--添加与修改的表单-->
                <el-dialog title="角色信息" :visible.sync="dialogVisible" width="30%">
                    <el-form label-width="80px" size="small" :model="form">
                        <el-form-item label="ID" style="display: none">
                            <el-input v-model="form.id" autocomplete="off" disabled></el-input>
                        </el-form-item>
                        <el-form-item label="名称" prop="roleId">
                            <el-input v-model="form.name" autocomplete="off"></el-input>
                        </el-form-item>
                        <el-form-item label="唯一标识" prop="roleId">
                            <el-input v-model="form.flag" autocomplete="off"></el-input>
                        </el-form-item>
                        <el-form-item label="描述">
                            <el-input v-model="form.description" autocomplete="off"></el-input>
                        </el-form-item>
                    </el-form>
                    <div slot="footer" class="dialog-footer">
                        <el-button @click="dialogVisible = false">取 消</el-button>
                        <el-button type="primary" @click="save">确 定</el-button>
                    </div>
                </el-dialog>

                <!--分配菜单的表单-->
                <el-dialog title="分配菜单" :visible.sync="menuDialogVisible" width="30%" style="padding:0 50px;">
                    <el-tree
                            :props="props"
                            :data="menuData"
                            show-checkbox
                            node-key="id"
                            ref="tree"
                            :default-expanded-keys="expends"
                            :default-checked-keys="checks">
                                             <span class="custom-tree-node" slot-scope="{ node, data }">
                                                <span><i :class="data.icon"></i> {{ data.name }}</span>
                                             </span>
                    </el-tree>


                    <div slot="footer" class="dialog-footer">
                        <el-button @click="menuDialogVisible = false">取 消</el-button>
                        <el-button type="primary" @click="saveRoleMenu">确 定</el-button>
                    </div>
                </el-dialog>
            </div>

        </div>
    </div>
</template>

<script>

    import request from "../utils/request";

    export default {
        name: 'Role',
        components: {},
        data() {
            return {
                form: {},
                roles: {},
                dialogVisible: false,
                menuDialogVisible: false,
                search: '',
                pageSize: 5,
                pageNum: 1,
                total: 20,
                tableData: [],
                college: [],
                status: [{name: "启用", value: "1"}, {name: "禁用", value: "0"}],
                multipleSelection: [],
                menuData: [],
                props: {
                    label: 'name',
                },
                expends: [],
                checks: [],
                roleId: 0,
                roleFlag: '',
                ids: []
            }
        },
        created() {
            this.load()
        },
        methods: {
            load() {
                this.pageNum = 1;
                // get方法需要params，post不要 "http://localhost:9090/role"
                request.get("/role", {
                    params: {
                        pageNum: this.pageNum,
                        pageSize: this.pageSize,
                        roleName: this.search,
                    }
                }).then(res => {
                    console.log("res:", res);
                    this.tableData = res.data.records;
                    this.total = res.data.total;
                })

                this.request.get("/menu/ids").then(r => {
                    this.ids = r.data
                })

            },
            add() {
                this.dialogVisible = true;
                this.form = {};
                this.form.useStatus = "1"; //初始化使用状态
            },
            save() {
                console.log("form:", this.form)
                if (this.form.id) { // 更新
                    request.post('/role/save', this.form).then(res => {
                        console.log("code:", res.code)
                        if (res.code == '200') {
                            this.$message.success("保存成功")
                        } else {
                            this.$message.error("保存失败")
                        }
                        this.load() //刷新表格
                        this.dialogVisible = false
                        console.log("success")
                    })
                } else { //新增
                    request.post("/role/save", this.form).then(res => {
                        console.log(res.data)
                        if (res.code == '200') {
                            this.$message.success("添加成功")
                        } else {
                            this.$message.error("添加失败")
                        }
                        this.load() //刷新表格
                        this.dialogVisible = false
                        console.log("success")
                    })
                }

            },
            handleEdit(index, row) {
                this.form = JSON.parse(JSON.stringify(row))
                this.dialogVisible = true
                console.log(row)
            },
            handleDelete(index, row) {
                console.log(row.id)
                //注意url/{路径}/
                this.request.delete("/role/delete/" + row.id).then(res => {
                    console.log(res)
                    if (res.data === true) {
                        this.$message.success("删除成功")
                        this.load()
                    } else {
                        this.$message.error("删除失败")
                    }
                })

            },
            handleSizeChange(pageSize) { //改变当前每页的个数触发
                this.pageSize = pageSize
                console.log(pageSize)
                this.load()
            },
            handleCurrentChange(pageNum) {  //改变当前页码触发
                this.pageNum = pageNum
                this.load()
            },
            async selectMenu(role) {
                this.roleId = role.id
                this.roleFlag = role.flag

                // 请求菜单数据
                this.request.get("/menu/findAll").then(res => {
                    this.menuData = res.data
                    // 把后台返回的菜单数据处理成 id数组
                    this.expends = this.menuData.map(v => v.id) //代码有问题
                    console.log("expends",this.expends)
                })
                this.request.get("/role/roleMenu/" + this.roleId).then(res => {
                    this.checks = res.data
                    console.log("checks:",this.checks)
                    this.request.get("/menu/ids").then(r => {
                        const ids = r.data
                        ids.forEach(id => {
                            if (!this.checks.includes(id)) {
                                // 可能会报错：Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'setChecked')
                                this.$nextTick(() => {
                                    this.$refs.tree.setChecked(id, false)
                                });
                            }
                        })

                    })
                    this.menuDialogVisible = true

                })
            },
            saveRoleMenu() {
                this.request.post("/role/roleMenu/" + this.roleId, this.$refs.tree.getCheckedKeys()).then(res => {
                    if (res.code === '200') {
                        this.$message.success("绑定成功")
                        this.menuDialogVisible = false

                        //操作管理员角色后需要重新登录
                        if (this.roleFlag === 'ROLE_ADMIN') {
                            this.$store.commit("logout")
                        }

                    } else {
                        this.$message.error(res.msg)
                    }
                })

                console.log("getkeys",this.$refs.tree.getCheckedKeys());
            },

        }
    }
</script>
